from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser
from rest_framework.response import Response
from django.core.files.storage import default_storage
from django.conf import settings
import uuid
import os
from PIL import Image
from io import BytesIO

class ImageUploadView(APIView):
    """
    文件上传接口
    POST /api/upload/
    参数：
    - image: 文件对象
    - type: 上传类型（review|avatar|dish等）
    """
    parser_classes = [MultiPartParser]
    
    ALLOWED_TYPES = ['review', 'avatar', 'dish']
    MAX_SIZE = 5 * 1024 * 1024  # 5MB
    ALLOWED_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.webp']

    def post(self, request):
        # 1. 验证基本参数
        if 'image' not in request.FILES:
            return Response({"error": "未上传文件"}, status=400)
        
        upload_type = request.data.get('type', 'review')
        if upload_type not in self.ALLOWED_TYPES:
            return Response({"error": "无效的上传类型"}, status=400)

        # 2. 验证文件
        uploaded_file = request.FILES['image']
        if uploaded_file.size > self.MAX_SIZE:
            return Response({"error": f"文件大小不能超过{self.MAX_SIZE//1024//1024}MB"}, status=400)
        
        ext = os.path.splitext(uploaded_file.name)[1].lower()
        if ext not in self.ALLOWED_EXTENSIONS:
            return Response({"error": "仅支持JPG/PNG/WEBP格式"}, status=400)

        # 3. 处理文件（压缩和重命名）
        try:
            # 打开图片并压缩
            img = Image.open(uploaded_file)
            if img.format == 'PNG':
                img = img.convert('P')
            
            output = BytesIO()
            img.save(output, format='WEBP', quality=85)
            output.seek(0)

            # 生成存储路径
            filename = f"{upload_type}/{uuid.uuid4().hex[:8]}.webp"
            filepath = default_storage.save(filename, output)

            # 4. 返回URL
            if settings.USE_S3:
                url = default_storage.url(filepath)
            else:
                url = f"{settings.MEDIA_URL}{filepath}"
            
            return Response({
                "url": url,
                "path": filepath,
                "size": output.tell(),
                "type": upload_type
            })
        except Exception as e:
            return Response({"error": f"文件处理失败: {str(e)}"}, status=500)